package com.iflytek.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iflytek.common.Result;
import com.iflytek.dao.OrderDao;
import com.iflytek.document.OrderDocument;
import com.iflytek.dto.OrderDTO;
import com.iflytek.dto.PageDTO;
import com.iflytek.enums.OrderStateEnum;
import com.iflytek.info.Cartinfo;
import com.iflytek.mapper.CartMapper;
import com.iflytek.mapper.GoodsMapper;
import com.iflytek.mapper.OrderMapper;
import com.iflytek.model.Cart;
import com.iflytek.model.Goods;
import com.iflytek.model.Order;
import com.iflytek.model.User;
import com.iflytek.service.GoodsService;
import com.iflytek.service.OrderService;
import com.iflytek.service.UserService;
import com.iflytek.utils.CopyUtil;
import com.iflytek.utils.DateUtils;
import com.iflytek.vo.CartVO;
import com.iflytek.vo.GoodsVO;
import com.iflytek.vo.OrderVO;
import com.iflytek.vo.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author h_t
 * @since 2023-09-23
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDao orderDao;
    @Resource
    private UserService userService;
    @Resource
    private CartMapper cartMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsService goodsService;



    /**
     * @return
     */
    @Override
    public Result<List<OrderVO>> findAll() {
        List<OrderVO> orderVOList = new ArrayList<>();
        Iterable<OrderDocument> all = orderDao.findAll();
        List<OrderDocument> orderDocumentList = new ArrayList<>();
        all.forEach(s->{
            orderDocumentList.add(s);
        });
        if (!StringUtils.isEmpty(orderDocumentList)){
            orderVOList = CopyUtil.copyList(orderDocumentList, OrderVO.class);
        }else {
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            List<Order> orderList = orderMapper.selectList(queryWrapper);
            orderVOList = CopyUtil.copyList(orderList, OrderVO.class);
        }
        return Result.success(orderVOList);
    }

    /**
     * saveOrder
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> saveOrder(OrderDTO dto,HttpServletRequest request) {
        User user = userService.getUserByToken(request);
        Date date = new Date();
        //Order order = new Order();
        if (dto == null) {
            return Result.error("1", "内容为空");
        }
        if (dto.getUserId()==null){
            dto.setUserId(user.getId());
        }
        if (dto.getCreateTime()==null){
            dto.setCreateTime(DateUtils.formatFullStr(date));
        }
        if (dto.getOrderNo()==null){
            dto.setOrderNo(DateUtils.formatSimpleStr(date));
        }
        Order order = CopyUtil.copy(dto, Order.class);
        if (StringUtils.isEmpty(order.getId())) {
            if (StringUtils.isEmpty(order)) {
                return Result.error("1", "保存失败");
            }
        }
        int insert = orderMapper.insert(order);
        if (insert == 0) {
            return Result.error("1", "保存失败");
        }else {
            OrderDocument copy = CopyUtil.copy(order, OrderDocument.class);
            orderDao.save(copy);
            return Result.success(true);
        }

    }

    /**
     * updateOrder
     * @param dto
     * @return
     */
    @Override
    public Result<Boolean> updateOrder(OrderDTO dto) {
        Order order = orderMapper.selectById(dto.getId());
        BeanUtils.copyProperties(dto, order);

        int count = orderMapper.updateById(order);
        if (count > 0) {
            orderDao.deleteById(dto.getId());
            OrderDocument copy = CopyUtil.copy(order, OrderDocument.class);
            orderDao.save(copy);
            return Result.success(true);
        } else {
            return Result.error("1", "更新失败");
        }
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result<OrderVO> findById(Long id) {
        OrderVO orderVO;
        if (id == null) {
            Result.error("401", "id为空");
        }
        Optional<OrderDocument> byId = orderDao.findById(id);
        OrderDocument orderDocument = byId.get();
        if (!StringUtils.isEmpty(orderDocument)){
            orderVO = CopyUtil.copy(orderDocument, OrderVO.class);
        }else {
            Order order = orderMapper.selectById(id);
            orderVO = CopyUtil.copy(order, OrderVO.class);
        }


        return Result.success(orderVO);
    }

    /**
     * @return
     */
    @Override
    public Result<PageVO<OrderVO>> findByFront(PageDTO<OrderDTO> dto,HttpServletRequest request) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(dto.getName())) {
            queryWrapper.lambda().like(Order::getState, dto.getName());
        }
        if (dto.getPageNum() == null) {
            dto.setPageNum(1);
        }
        if (dto.getSize() == null) {
            dto.setSize(5);
        }
        User user = userService.getUserByToken(request);
        //分页
        PageHelper.startPage(dto.getPageNum(), dto.getSize());
        List<OrderVO> orderVOS = new ArrayList<>();
        Iterable<OrderDocument> all = orderDao.findAll();
        List<OrderDocument> orderDocuments = new ArrayList<>();
        all.forEach(s->{
            orderDocuments.add(s);
        });

        if (!StringUtils.isEmpty(orderDocuments)){
            orderVOS = CopyUtil.copyList(orderDocuments, OrderVO.class);
            /*orderVOS = orderVOS.stream()
                    .filter(order -> order.getUserId().equals(user.getId()))
                    .collect(Collectors.toList());*/

        }else {
            queryWrapper.lambda().eq(Order::getUserId, user.getId());
            List<Order> orders = orderMapper.selectList(queryWrapper);
            orderVOS = CopyUtil.copyList(orders, OrderVO.class);
        }
        orderVOS.forEach(s->{
            QueryWrapper<Cart> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(Cart::getUserId,s.getUserId());
            List<Cart> carts = cartMapper.selectList(queryWrapper1);
            List<CartVO> cartVOS = CopyUtil.copyList(carts, CartVO.class);
            cartVOS.forEach(c->{
                QueryWrapper<Goods> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.lambda().eq(Goods::getId,c.getGoodsId());
                Goods goods = goodsMapper.selectOne(queryWrapper2);
//                GoodsVO goodsVO = CopyUtil.copy(goods, GoodsVO.class);
                GoodsVO goodsVO = CopyUtil.copy(goods, GoodsVO.class);
                c.setGoods(goodsVO);
            });
            s.setCarts(cartVOS);
        });
        PageInfo<Order> orderPageInfo = new PageInfo<>();
        PageVO<OrderVO> pageVO = new PageVO<>();
        BeanUtils.copyProperties(dto, pageVO);
        pageVO.setTotal(orderPageInfo.getTotal());
        pageVO.setRecords(orderVOS);
        return Result.success(pageVO);

    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result<Boolean> findByPay(Long id) {
        Order order;
        if (id == null) {
            Result.error("401", "id为空");
        }
        Optional<OrderDocument> byId = orderDao.findById(id);
        OrderDocument orderDocument = byId.get();

        if (!StringUtils.isEmpty(orderDocument)){
            order = CopyUtil.copy(orderDocument, Order.class);
        }else {
            order = orderMapper.selectById(id);
        }

        boolean equals = order.getState().equals(OrderStateEnum.TBP.getDesc());
        if (equals) {
            order.setState(OrderStateEnum.TBS.getDesc());
            orderMapper.updateById(order);
            orderDao.deleteById(order.getId());
            OrderDocument copy = CopyUtil.copy(order, OrderDocument.class);
            orderDao.save(copy);
            return Result.success();
        }else {
            return Result.error("402", "该用户不属于未付款状态");
        }


    }


    @Override
    public Result<Cartinfo> findByPre(HttpServletRequest request) {
        User user = userService.getUserByToken(request);
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Cart::getUserId,user.getId());
        List<Cart> carts = cartMapper.selectList(wrapper);
        List<CartVO> cartVOS = CopyUtil.copyList(carts, CartVO.class);
        Cartinfo cartinfo = new Cartinfo();



        BigDecimal totalPrice = new BigDecimal("0");
        BigDecimal origPrice = new BigDecimal("0");
        for(CartVO cartVO:cartVOS){
            Long goodsId = cartVO.getGoodsId();
            Goods goods = goodsService.getById(goodsId);
            GoodsVO goodsVO = CopyUtil.copy(goods, GoodsVO.class);
            goodsVO.setRealPrice(goodsVO.getPrice().multiply(BigDecimal.valueOf(goods.getDiscount())));
            cartVO.setGoods(goodsVO);

            totalPrice = totalPrice.add(goodsVO.getRealPrice().multiply(BigDecimal.valueOf(cartVO.getCount())));
            origPrice = origPrice.add(goodsVO.getPrice().multiply(BigDecimal.valueOf(cartVO.getCount())));

        }
        cartinfo.setList(cartVOS);
        cartinfo.setTotalPrice(totalPrice);
        cartinfo.setDiscount(origPrice);
        return Result.success(cartinfo);
    }


    @Override
    public Result<OrderVO> deleteById(Long id) {

        if (id == null) {
            Result.error("401", "id为空");
        }
        int i = orderMapper.deleteById(id);
        if (i > 0) {
            orderDao.deleteById(id);
            Result.success();
        } else {

            Result.error("204", "错误");
        }
        return Result.success();
    }

    @Override
    public Result<PageVO<OrderVO>> findPage(PageDTO<OrderDTO> dto) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(dto.getName())) {
            queryWrapper.lambda().like(Order::getOrderNo, dto.getName());
        }
        if (dto.getPageNum() == null) {
            dto.setPageNum(1);
        }
        if (dto.getSize() == null) {
            dto.setSize(5);
        }
        //分页
        PageHelper.startPage(dto.getPageNum(), dto.getSize());

        List<Order> orders = orderMapper.selectList(queryWrapper);

        List<OrderVO> orderVOList = new ArrayList<>();
        orderVOList = CopyUtil.copyList(orders, OrderVO.class);

        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        PageVO<OrderVO> pageVO = new PageVO<>();
        BeanUtils.copyProperties(dto, pageVO);
        pageVO.setTotal(orderPageInfo.getTotal());
        pageVO.setRecords(orderVOList);
        return Result.success(pageVO);
    }

}
